package com.sun.btrace.cmd;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import com.sun.btrace.CommandListener;
import com.sun.btrace.client.Client;
import com.sun.btrace.comm.Command;
import com.sun.btrace.comm.DataCommand;
import com.sun.btrace.comm.ErrorCommand;
import com.sun.btrace.comm.ExitCommand;

public class submit extends CommandCase {
	private boolean exiting ;
	public submit(){
		super() ;
		exiting = false ;
		
	}
	 
	@Override
	public void help() {
		// TODO Auto-generated method stub
		String help="submit /path/of/the/file.java  -cp /used/jar.jar" ;
		context.print(help) ;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	
	@Override
	public void realCMDAction(String... args) {
		try {
			action(args);
		} catch (Exception e) {
			//e.printStackTrace(out);
			context.println(e.getMessage()) ;
		}
	}
	public void action(String... args) throws IOException{
		String fileName= args[0];
		String classPath = ".";
		String includePath = null;

		int count = 0;
		boolean includePathDefined = false;
		String[] btraceArgs = new String[0];
		for (count = 1; count < args.length; ++count) {
			if ((args[count].equals("-cp") || args[count]
					.equals("-classpath"))) {
				classPath = args[++count];
				context.println("accepting classpath " + classPath);
			}
		}
			Client client = this.context.getClient() ;
					;
//			client.login();
			
			if (!new File(fileName).exists()) {
				context.println("File not found: " + fileName );
				return ;
			}

			byte[] code = client.compile(fileName, classPath, includePath);
			if (code == null) {
					System.err.println("BTrace compilation failed");
					return ;
				}
			context.println("btrace get host " + context.getHost());
			if (!client.login()) {
				System.err.println("fail to login with psw, please try again.");
				return;
			}

			context.registerExitHook(client);
			if (con != null) {
				context.registerSignalHandler(client);
			}
			else 
				return ;
			context.println("submitting the BTrace program");
			client.submit(fileName, code, btraceArgs,context.createCommandListener(client));
	}
	
}
